package org.jaaksi.androidforflutterdemo;

import android.app.Application
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor
import io.flutter.view.FlutterMain
import libcore.config.LibConfig
import org.jaaksi.androidforflutterdemo.config.UriConfig
import org.jaaksi.library.FunctionBus

const val home_page_engine_id = "home_page_engine_id"

class MyApplication : Application() {
  private lateinit var flutterEngine: FlutterEngine

  override fun onCreate() {
    super.onCreate()
    // 注册
    FunctionBus.addFunction(NetworkFunctionImp())
    LibConfig.init(this, LibCallback())

// Instantiate a FlutterEngine.
    // Engine就是flutter运行的环境，初始化各种MethodChannel，最后注册插件
    flutterEngine = FlutterEngine(this)
    // Configure an initial route.
    flutterEngine.navigationChannel.setInitialRoute("home_page")
    // Start executing Dart code to pre-warm the FlutterEngine.
    flutterEngine.dartExecutor.executeDartEntrypoint(
      DartExecutor.DartEntrypoint.createDefault()
    )
    // Cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
    FlutterEngineCache
      .getInstance()
      .put(home_page_engine_id, flutterEngine)
  }

  //    释放flutter引擎
  override fun onTerminate() {
    flutterEngine.destroy()
    super.onTerminate()
  }

  private class LibCallback : LibConfig.Callback {
    override fun isDebug(): Boolean {
      return BuildConfig.DEBUG
    }

    override fun getBaseUrl(): String {
      return UriConfig.getBaseUrl();
    }
  }
}